package com.momo.hotel.controller;

import com.alibaba.fastjson.JSON;
import com.momo.hotel.api.SmsSingleSender;
import com.momo.hotel.api.SmsSingleSenderResult;
import com.momo.hotel.api.email.SendEmail;
import com.momo.hotel.dao.pojo.TbUser;
import com.momo.hotel.service.UserService;
import com.momo.hotel.utils.SendQQMailUtil;
import com.momo.hotel.utils.UploadFile;
import com.momo.hotel.vo.PhoneMassage;
import com.momo.hotel.vo.VoUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;


/**
 * @version 1.0.0
 * @auther Snake
 * @date 2019/7/1 16:53
 */

@Controller
public class UserController {
    TbUser tbUser = new TbUser();
    String str = new String();
    List<TbUser> list ;
    private static String code;

    @Resource
    UserService userService;



    @RequestMapping(value = "/checkUserName",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public boolean checkUserName(@RequestBody VoUser user){
        return userService.checkUsername(user);
    }

    @ResponseBody
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public Map<String, Object> upload(MultipartFile dropzFile, HttpServletRequest request) {
        System.out.println("inner upload");
        System.out.println(dropzFile);
        Map<String, Object> result = new HashMap<String, Object>();

        // 获取上传的原始文件名
        String fileName = dropzFile.getOriginalFilename();
        // 设置文件上传路径
        String filePath = request.getSession().getServletContext().getRealPath("/static/upload");


        // 获取文件后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());

        // 判断并创建上传用的文件夹
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 重新设置文件名为 UUID，以确保唯一
        file = new File(filePath, UUID.randomUUID() + fileSuffix);
        System.out.println(file.getAbsolutePath());
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            // 写入文件
            dropzFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }






        // 返回 JSON 数据，这里只带入了文件名
        result.put("fileName", file.getName());
        return result;
    }

    @RequestMapping(value = "/userRegister",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public boolean registerUser(@RequestBody VoUser user) throws MessagingException {

        String jsonString = JSON.toJSONString(user);
        //System.out.println(jsonString);
        TbUser tbUser = JSON.parseObject(jsonString, TbUser.class);




        return  userService.addUser(tbUser);
    }

    @RequestMapping(value = "userLogin",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public boolean loginUser(@RequestBody VoUser user,HttpServletRequest request){
        String username = user.getUsername();
        tbUser = userService.loginUserByUserName(username);

        request.getSession().setAttribute("user", tbUser);
        Object user1 = request.getSession().getAttribute("user");
        System.out.println("11111111111"+user1.toString());

        return userService.loginUser(tbUser);
    }

    @RequestMapping(value = "/registerPhone",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object registerPhone(@RequestBody VoUser user) throws MessagingException {

        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);
        TbUser tbUser = JSON.parseObject(jsonString, TbUser.class);

        PhoneMassage pm = new PhoneMassage();
        if (user.getCode().equals(code)){
            boolean b = userService.addUser(tbUser);
            if (b){
                pm.setMsg("成功");
                return true;
            }else {

            }
        }
        pm.setMsg("验证码错误");
        return false;
    }

    @RequestMapping(value = "sendMassage",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public void sendMassage(@RequestBody VoUser user) throws MessagingException {

        //发送短信
        Random random = new Random();
        str="";
        for (int i = 0; i < 4; i++) {
            str += Integer.toString(random.nextInt(10)+1);
        }

        code = str;
        //System.out.println("验证码："+code);


        //请根据实际 accesskey 和 secretkey 进行开发，以下只作为演示 sdk 使用
        String accesskey = "5d1c5c4487b65f0677884a98";
        String secretkey ="1f33f8ff7cc048519024d7d9a5a9ba72";
        //手机号码
        String phoneNumber = user.getUsername();
        //System.out.println("手机号"+phoneNumber);
        //初始化单发
        SmsSingleSender singleSender = null;
        try {
            singleSender = new SmsSingleSender(accesskey, secretkey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        SmsSingleSenderResult singleSenderResult=null;

        //普通单发,注意前面必须为【】符号包含，置于头或者尾部。
        try {
            singleSenderResult = singleSender.send(0, "86", phoneNumber, "【陌陌酒店平台】尊敬的用户：您的验证码："+code+"，工作人员不会索取，请勿泄漏。", "", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(singleSenderResult);


        //语音验证码发送
        //SmsVoiceVerifyCodeSender smsVoiceVerifyCodeSender = new SmsVoiceVerifyCodeSender(accesskey,secretkey);
        //SmsVoiceVerifyCodeSenderResult smsVoiceVerifyCodeSenderResult = smsVoiceVerifyCodeSender.send("86",phoneNumber, "444144",2,"");
        //System.out.println(smsVoiceVerifyCodeSenderResult);

    }


    @RequestMapping(value = "/sendEmail",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public void sendEmail(@RequestBody VoUser user) throws MessagingException {

        //发送邮箱
        Random random = new Random();
        str="";
        for (int i = 0; i < 4; i++) {
            str += Integer.toString(random.nextInt(10)+1);
        }

        code = str;
        System.out.println(code);


        try {
            SendEmail.sendQQMails(user.getUsername(),"验证码："+code);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequestMapping(value = "/registerEmail",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object registerEmail(@RequestBody VoUser user) throws MessagingException {

        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);
        TbUser tbUser = JSON.parseObject(jsonString, TbUser.class);

        PhoneMassage pm = new PhoneMassage();
        if (user.getCode().equals(code)){
            boolean b = userService.addUser(tbUser);
            if (b){
                pm.setMsg("成功");
                return pm;
            }else {
                pm.setMsg("验证码错误");
                return pm;
            }
        }
        return pm;
    }

    @RequestMapping(value = "/loginOut",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    @ResponseBody
    public void loginOut(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("user");
        response.setContentType("text/html;charset=utf-8");
        try {
            response.getWriter().print("<script>alert('注销成功');location='index.html';</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户修改
     * @param user
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadUser",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object uploadUser(@RequestBody VoUser user,HttpServletRequest request){
        TbUser user1 = (TbUser) request.getSession().getAttribute("user");

        user.setId(user1.getId());
        boolean b = userService.uploadUser(user);
        return b;
    }

    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object uploadFile(HttpServletRequest request , @RequestParam(name = "file",required = true) MultipartFile file){
        //得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
        String savePath = "/static/upload";
        String newFileName = null;
        TbUser user1 = null;
        try {
             newFileName = UploadFile.uploadFile(request, file, savePath);
             user1 = (TbUser) request.getSession().getAttribute("user");

        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        user1.setPhoto(newFileName);
        boolean b = userService.uploadUser(user1);

        return  newFileName ;
    }

    @RequestMapping(value = "/uploadPassword",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object uploadPassword(@RequestParam String oldPassword,String password, HttpServletRequest request){


        TbUser user1 = (TbUser) request.getSession().getAttribute("user");
        //System.out.println("777777777777777777"+oldPassword+"  "+password);
        if ( user1.getPassword().equals(oldPassword)){
            user1.setPassword(password);
            boolean b = userService.uploadUser(user1);
            return b;
        }
       return false;
    }

    @RequestMapping(value = "/getUserBySession",method = RequestMethod.POST)
    @ResponseBody
    public Object getUserBySession(HttpServletRequest request){
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        return user;
    }

}
